package cn.tp.ksoft.civil_driver.module;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import cn.tp.ksoft.civil_driver.DriverBaseActivity;
import cn.tp.ksoft.civil_driver.R;
import cn.tp.ksoft.civil_driver.bean.DriverDto;
import cn.tp.ksoft.civil_driver.bean.OrderBean;
import cn.tp.ksoft.civil_driver.bean.OrderDetailBean;
import cn.tp.ksoft.civil_driver.bean.ResultBean;
import cn.tp.ksoft.civil_driver.module.login.RegisterActivity;
import cn.tp.ksoft.civil_driver.module.mime.MimeActivity;
import cn.tp.ksoft.civil_driver.module.order.FinishOrderDetailActivity;
import cn.tp.ksoft.civil_driver.module.order.OrderDetailActivity;
import cn.tp.ksoft.civil_driver.request.DriverOrderRequest;
import cn.tp.ksoft.civil_driver.request.DriverRequest;
import cn.tp.ksoft.civil_driver.utils.Constants;
import cn.tp.ksoft.civil_driver.utils.TimestampTypeAdapter;
import cn.tp.ksoft.civil_driver.view.simple.SpaceItemDecoration;
import cn.tp.ksoft.library_civil.utils.DateUtil;
import cn.tp.ksoft.library_civil.utils.StringUtils;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;

/**
 * Created by zhusong on 16/4/20.
 */
public class MainActivity extends DriverBaseActivity implements View.OnClickListener{

    private final int ITEM_SPACE = 10;// dp
    private final int REQUEST_REAPPLY = 1;
    private final int REQUEST_DETAIL = 2;
    private final int REQUEST_FINISH = 3;

    private ImageView mIconIv;
    private TextView mNameTv;
    // content
    private RecyclerView mRv;
    private MainOrderAdapter mAdapter;
    private LinearLayoutManager mLayoutManager;
    private LayoutInflater mInflater;

    // status
    private TextView mStatusTv;
    private Drawable mStatusDrawable;

    private DriverRequest driverRequest;
    private DriverDto driverDto;
    private DriverOrderRequest orderRequest;
    private PtrClassicFrameLayout frameLayout;
	private Gson gson;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.driver_activity_main);
        driverRequest = new DriverRequest(this, new WeakHandler(this));
        orderRequest = new DriverOrderRequest(this, new WeakHandler(this));

        mInflater = LayoutInflater.from(this);
        findViewById(R.id.btn_mine).setOnClickListener(this);
        findViewById(R.id.btn_chat).setOnClickListener(this);
        mIconIv = (ImageView) findViewById(R.id.iv_icon);
        mNameTv = (TextView) findViewById(R.id.tv_name);
        mRv = (RecyclerView) findViewById(R.id.rv);
        mAdapter = new MainOrderAdapter();
        mLayoutManager = new LinearLayoutManager(this);
        mRv.setAdapter(mAdapter);
        mRv.setLayoutManager(mLayoutManager);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        mRv.addItemDecoration(new SpaceItemDecoration(Math.round(ITEM_SPACE * dm.density)));
        mStatusTv = (TextView) findViewById(R.id.tv_status);
        mStatusDrawable = getResources().getDrawable(R.drawable.driver_arrow_detail);
        if (null != mStatusDrawable) {
            mStatusDrawable.setBounds(0, 0,
                    mStatusDrawable.getMinimumWidth(), mStatusDrawable.getMinimumHeight());
        }
        frameLayout = (PtrClassicFrameLayout) findViewById(R.id.ptr);
        frameLayout.setPtrHandler(new PtrDefaultHandler() {

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                orderRequest.listDriver();
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return super.checkCanDoRefresh(frame, mRv, header);
            }
        });

        //↓add by Wendy Ban
		GsonBuilder gsonBuilder = new GsonBuilder();
		gsonBuilder.registerTypeAdapter(Date.class, new TimestampTypeAdapter());
		gson = gsonBuilder.create();
		//↑
        driverRequest.getInfo();
    }

    /**
     *  1:待审核  2:通过  3:不通过
     */
    private void updateContent(int status) {
    	mNameTv.setText(driverDto.getName());
        String headImg = driverDto.getHeadImg();
        if (!TextUtils.isEmpty(headImg)) {
            ImageLoader.getInstance().displayImage(Constants.APK_DOWNLOAD_PATH + headImg, mIconIv);
        }
        if (status == Constants.STATUS_AUDIT_FAILURE) {
            mRv.setVisibility(View.GONE);
            mStatusTv.setCompoundDrawables(null, null, mStatusDrawable, null);
            mStatusTv.setVisibility(View.VISIBLE);
            mStatusTv.setOnClickListener(this);
            mStatusTv.setText(driverDto.getUnPassReason());
        } else if (status == Constants.STATUS_AUDITING) {
            mRv.setVisibility(View.GONE);
            mStatusTv.setCompoundDrawables(null, null, null, null);
            mStatusTv.setVisibility(View.VISIBLE);
            mStatusTv.setOnClickListener(null);
            mStatusTv.setText(getString(R.string.driver_tip_is_auditing));
        } else {
            mRv.setVisibility(View.VISIBLE);
            mStatusTv.setVisibility(View.GONE);
            frameLayout.autoRefresh();
        }
    }

    private void updateList(List<OrderBean> list){
    	mAdapter.setList(list, true);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_REAPPLY) {
            if (resultCode == RESULT_OK) {
                driverRequest.getInfo();
            }
        } else if (requestCode == REQUEST_DETAIL || requestCode == REQUEST_FINISH) {
            if (resultCode == RESULT_OK) {
                frameLayout.autoRefresh();
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_mine : {
                Intent intent = new Intent(this, MimeActivity.class);
                startActivity(intent);
                break;
            }
            case R.id.btn_chat : {
                break;
            }
            case R.id.tv_status : {
                Intent intent = new Intent(this, RegisterActivity.class);
                intent.putExtra(Constants.KEY_ISREAPPLY, true);
                startActivityForResult(intent, REQUEST_REAPPLY);
                break;
            }
        }
    }

    class MainOrderHolder extends RecyclerView.ViewHolder {
    	TextView tvTime;
    	TextView tvAddr;
    	TextView tvShengysj;
    	TextView tvStatus;

    	public MainOrderHolder(View itemView) {
            super(itemView);
            tvAddr = (TextView) itemView.findViewById(R.id.tv_driver_main_item_addr);
            tvShengysj = (TextView)itemView.findViewById(R.id.tv_driver_main_item_shengyusj);
            tvStatus = (TextView) itemView.findViewById(R.id.tv_driver_main_item_status);
            tvTime = (TextView) itemView.findViewById(R.id.tv_driver_main_item_time);
        }
    }
    /***
	 * 
	 * @param time2 下单时间
	 * @param maxtime 最大允许时间
	 */
	private long getShengyusj(long time2,int maxtime){
		long time = 0;
		time = (maxtime*60*1000)-(new Date().getTime()-time2); 
		return time;
	}
	
    class MainOrderAdapter extends RecyclerView.Adapter<MainOrderHolder> {
    	
    	private List<TimeOrder> mList;
    	 Handler handler = new Handler();  
    	 Runnable runnable = new Runnable() {  
    		 @Override  
    		 public void run() {
    			 refreshList();
    			 handler.postDelayed(this, 1000);  
    		 }  
    	 };
    	public void setList(List<OrderBean> orderList,boolean isReset) {
    		if(mList == null){
    			mList = new CopyOnWriteArrayList<TimeOrder>();
    		}
    		if(isReset){
    			mList.clear();
    			handler.removeCallbacks(runnable); 
    		}
    		if(!StringUtils.isEmpty(orderList)){
    			for(int i = 0;i < orderList.size();i++){
    				TimeOrder timeOrder =new TimeOrder();
    				timeOrder.setOrderBean(orderList.get(i));
                    OrderDetailBean detailBean = gson.fromJson(timeOrder.getOrderBean().getDetail(),
                            OrderDetailBean.class);
                    timeOrder.getOrderBean().setDetailBean(detailBean);
    				timeOrder.setTime(getShengyusj(orderList.get(i).getOrderTime().getTime(),15));
    				mList.add(timeOrder);
    			}
    		}
    		notifyDataSetChanged();
    		handler.postDelayed(runnable, 1000);
    	}
    	private void refreshList(){
    		if(!StringUtils.isEmpty(mList)){
    			synchronized(mList){
    				Iterator<TimeOrder> it = mList.iterator();
    				while(it.hasNext()) { 
    					TimeOrder timeOrder = it.next();
    					if(timeOrder.getOrderBean().getStatus()==21){
    						if(timeOrder.getTime()> 0){
    							timeOrder.setTime(timeOrder.getTime()-1000);
    						}else {
    							mList.remove(timeOrder);
    						}
    					}
    				} 
    			}
    			notifyDataSetChanged();
    		}
    	}
        @Override
        public MainOrderHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            return new MainOrderHolder(mInflater.inflate(R.layout.driver_main_item, viewGroup, false));
        }

        @Override
        public void onBindViewHolder(MainOrderHolder holder, final int position) {
        	TimeOrder timeOrder = mList.get(position);
    		OrderBean orderBean = timeOrder.getOrderBean();
    		OrderDetailBean detailBean = orderBean.getDetailBean();
    		if(orderBean !=null && detailBean !=null){
    			holder.tvAddr.setText(StringUtils.replaceNull(detailBean.getStartAddress()));
    			holder.tvTime.setText(DateUtil.D2Syrsf(detailBean.getBycarStartTime())+"出发|"+"包车"+DateUtil.hours2day(detailBean.getBycarLong()));
    			holder.tvStatus.setText(orderBean.getStatusName());
    		}
    		if(orderBean.getStatus()== 21){
    			holder.tvShengysj.setText(DateUtil.D2Sfm(new Date(timeOrder.getTime())));
    		}else {
    			holder.tvShengysj.setText("");
    		}
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    OrderBean bean = mList.get(position).getOrderBean();
                    if (bean.getStatus() == 21) {
                        Intent intent = new Intent(MainActivity.this, OrderDetailActivity.class);
                        intent.putExtra(Constants.KEY_ORDER_BEAN, bean);
                        startActivityForResult(intent, REQUEST_DETAIL);
                    } else {
                        Intent intent = new Intent(MainActivity.this, FinishOrderDetailActivity.class);
                        intent.putExtra(Constants.KEY_ORDER_BEAN, bean);
                        startActivityForResult(intent, REQUEST_FINISH);
                    }
                }
            });
        }

        @Override
        public int getItemCount() {
            return mList==null?0:mList.size();
        }
    }

    @Override
    protected void handleFailureResult(int what, @NonNull ResultBean result) {
        super.handleFailureResult(what, result);
        if (what == LISTDRIVER) {
            frameLayout.refreshComplete();
        }
    }

    @Override
    protected void handleSuccessResult(int what, @NonNull ResultBean result) {
        switch (what) {
            case GETINFO : {
                // update info
                driverDto = (DriverDto) result.getData();
                boolean isOvered = driverDto.getInfoOvered();
                if (!isOvered) {
                    Intent intent = new Intent(this, RegisterActivity.class);
                    intent.putExtra(Constants.KEY_ISREAPPLY, true);
                    startActivity(intent);
                    finish();
                    return;
                }

                int status = driverDto.getAuditStatus();
                updateContent(status);
                //↓ 测试 跳过填信息、验证等
                /*updateContent(Constants.STATUS_AUDIT_SUCCESS);
                orderRequest.listDriver();*/
                //↑ 测试
                break;
            }

            case LISTDRIVER : {
                // update list
                frameLayout.refreshComplete();
                if (!StringUtils.isEmpty(result.getData())) {
                    List<OrderBean> list = gson.fromJson(gson.toJson(result.getData()),
                            new TypeToken<List<OrderBean>>() { }.getType());
                    updateList(list);
                }
                break;
            }
        }
    }

	class TimeOrder{
		private OrderBean orderBean;
		private long time;
		public OrderBean getOrderBean() {
			return orderBean;
		}
		public void setOrderBean(OrderBean orderBean) {
			this.orderBean = orderBean;
		}
		public long getTime() {
			return time;
		}
		public void setTime(long time) {
			this.time = time;
		}
		
	}
}
